import { cleanEnv, str, port, num, url } from 'envalid';
import { logger } from './logger';

/**
 * 验证必需的环境变量
 * 如果缺少必需的环境变量，将抛出错误
 */
export const validateEnv = () => {
  try {
    const env = cleanEnv(process.env, {
      // Server
      NODE_ENV: str({ choices: ['development', 'test', 'production'] }),
      PORT: port({ default: 3000 }),

      // Database
      MONGODB_URI: url(),

      // JWT
      JWT_SECRET: str(),
      JWT_EXPIRES_IN: str({ default: '7d' }),

      // Redis (Optional)
      REDIS_URI: str({ default: undefined }),

      // Logging
      LOG_LEVEL: str({
        choices: ['error', 'warn', 'info', 'debug'],
        default: 'info'
      }),
      LOG_FILE_PATH: str({ default: 'logs/app.log' }),

      // AI Service
      AI_SERVICE_URL: url(),
      AI_SERVICE_KEY: str(),

      // Rate Limiting
      RATE_LIMIT_WINDOW: num({ default: 900000 }), // 15 minutes
      RATE_LIMIT_MAX: num({ default: 100 }),

      // Email (Optional)
      SMTP_HOST: str({ default: undefined }),
      SMTP_PORT: port({ default: 587 }),
      SMTP_USER: str({ default: undefined }),
      SMTP_PASS: str({ default: undefined })
    });

    logger.info('Environment validation successful', {
      nodeEnv: env.NODE_ENV,
      port: env.PORT,
      logLevel: env.LOG_LEVEL
    });

    return env;
  } catch (error) {
    logger.error('Environment validation failed:', error);
    throw error;
  }
};

/**
 * 验证敏感配置
 * 用于检查关键安全设置是否合理
 */
export const validateSecurityConfig = () => {
  const { JWT_SECRET, NODE_ENV } = process.env;

  // 检查JWT密钥强度
  if (JWT_SECRET && JWT_SECRET.length < 32) {
    logger.warn('JWT_SECRET is too weak. Recommend at least 32 characters.');
  }

  // 生产环境特殊检查
  if (NODE_ENV === 'production') {
    if (JWT_SECRET === 'your-jwt-secret-key') {
      throw new Error('Default JWT_SECRET detected in production environment');
    }

    if (!process.env.REDIS_URI) {
      logger.warn('Redis is recommended for production environment');
    }
  }
};

/**
 * 检查可选功能的配置完整性
 */
export const checkOptionalFeatures = () => {
  const optionalFeatures = {
    redis: !!process.env.REDIS_URI,
    email: !!(
      process.env.SMTP_HOST &&
      process.env.SMTP_USER &&
      process.env.SMTP_PASS
    )
  };

  logger.info('Optional features status:', optionalFeatures);
  return optionalFeatures;
};
